const { exec } = require('child_process');
const path = require('path');
const chalk = require('chalk');

// 定义项目路径
const mainPath = __dirname;
const vue2Path = path.join(__dirname, '../wujie-vue2-sub');
const vue3Path = path.join(__dirname, '../wujie-vue3-sub');

// 定义应用信息
const apps = [
  { name: '主应用', path: mainPath, port: 8080 },
  { name: 'Vue2子应用', path: vue2Path, port: 8082 },
  { name: 'Vue3子应用', path: vue3Path, port: 8083 }
];

// 检查是否需要安装依赖
const checkAndInstall = (projectPath) => {
  return new Promise((resolve, reject) => {
    if (!require('fs').existsSync(path.join(projectPath, 'node_modules'))) {
      console.log(chalk.yellow(`正在安装 ${path.basename(projectPath)} 依赖...`));
      exec('npm install', { cwd: projectPath }, (error) => {
        if (error) {
          reject(error);
          return;
        }
        resolve();
      });
    } else {
      resolve();
    }
  });
};

// 启动项目
const startProject = (app) => {
  return new Promise((resolve) => {
    console.log(chalk.cyan(`正在启动 ${app.name}...`));
    const child = exec('npm run serve', { cwd: app.path });
    
    let isStarted = false;
    
    child.stdout.on('data', (data) => {
      // 只输出重要信息
      if (data.includes('App running at:') || data.includes('Local:')) {
        if (!isStarted) {
          isStarted = true;
          console.log(chalk.green(`✓ ${app.name}已启动: http://localhost:${app.port}`));
          resolve();
        }
      } else if (data.includes('ERROR')) {
        console.log(chalk.red(`[${app.name}] ${data}`));
      }
    });
    
    child.stderr.on('data', (data) => {
      if (data.includes('ERROR')) {
        console.error(chalk.red(`[${app.name}] ${data}`));
      }
    });
  });
};

// 主函数
async function startAll() {
  console.log(chalk.blue('=== 无界微前端启动程序 ==='));
  
  try {
    // 检查并安装依赖
    console.log(chalk.blue('\n[1/2] 检查依赖...'));
    await Promise.all(apps.map(app => checkAndInstall(app.path)));
    
    // 启动所有项目
    console.log(chalk.blue('\n[2/2] 启动应用...\n'));
    await Promise.all(apps.map(app => startProject(app)));
    
    // 所有应用启动成功后显示汇总信息
    console.log(chalk.green('\n=== 所有应用启动成功 ==='));
    console.log(chalk.white('\n访问地址：'));
    apps.forEach(app => {
      console.log(chalk.cyan(`${app.name}: `) + chalk.yellow(`http://localhost:${app.port}`));
    });
    console.log(chalk.gray('\n提示：主应用中已集成所有子应用，直接访问主应用即可\n'));

  } catch (error) {
    console.error(chalk.red('\n启动失败：'), error);
    process.exit(1);
  }
}

startAll(); 